package com.hongxun.budget.ui.activity.sg;

import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.InputDialog2;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.sg.CGoodsDetailEntity;
import com.hongxun.greenentity.tk.BDeviceEntity;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 选择物资
 */
public class SelectSuppliesActivity extends BaseActivity {

    @BindView(R.id.tvType1)
    TextView tvType1;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.list)
    RecyclerView leftLView;
    @BindView(R.id.search_info)
    EditText searchInfo;
    @BindView(R.id.list2)
    RecyclerView rightLView;

    private String uuid;//记录uuid
    private List<String> labels = new ArrayList<>();
    private List<String> leftDatas = new ArrayList<>();//左边展示选项
    private SuperAdapter<String> leftAdapter;
    private int left = -1;//记录left的选择
    private int pos = -1;//记录spinner的选择
    //设备物资数据
    private List<BDeviceEntity> deviceEntities = new ArrayList<>();
    private SuperAdapter<BDeviceEntity> dAdapter;
    //材料物资数据
    private List<BMaterialEntity> materialEntities = new ArrayList<>();
    private SuperAdapter<BMaterialEntity> mAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.sg_activity_select_supplies;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        uuid = getIntent().getStringExtra("uuid");
        pos = getIntent().getIntExtra("pos", 0);
        //1：顶部类别选择
        if (pos == 0) {
            tvTitle.setText("设备物资");
            List<BDeviceEntity> deviceEntityList = SgDBUtils.getBDeviceEntityList(2, "1");
            for (BDeviceEntity entity : deviceEntityList) {
                labels.add(entity.getDMidtype());
            }
        } else {
            tvTitle.setText("材料物资");
            List<BMaterialEntity> materialEntityList = SgDBUtils.getBMaterialEntityList(2, "1");
            for (BMaterialEntity entity : materialEntityList) {
                labels.add(entity.getMMidtype());
            }
        }
        if (!labels.isEmpty()) tvType1.setText(labels.get(0));
        //2：左边列表
        leftLView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        leftLView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        leftLView.setAdapter(leftAdapter = new SuperAdapter<String>(R.layout.content_adddevice_left) {
            @Override
            public void bindView(ViewHolder viewHolder, final String s, final int i) {
                TextView t = viewHolder.getView(R.id.label);
                t.setText(s);
                if (i == left) {
                    t.setBackgroundResource(R.drawable.view_bottom_textpre);
                } else {
                    t.setBackgroundResource(R.color.white);
                }
                t.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        left = i;
                        leftAdapter.notifyDataSetChanged();
                        getRightData();
                    }
                });
            }
        });
        leftAdapter.setData(leftDatas);
        leftAdapter.setEmptyDataView(R.layout.view_empty);
        //3：设备物资
        rightLView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        dAdapter = new SuperAdapter<BDeviceEntity>(R.layout.content_add_device) {
            @Override
            public void bindView(ViewHolder viewHolder, final BDeviceEntity bDeviceEntity, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(StringUtils.getNull(bDeviceEntity.getDName()));
                ((TextView) viewHolder.getView(R.id.type)).setText(StringUtils.getNull(bDeviceEntity.getDLabel()));
                ((TextView) viewHolder.getView(R.id.parameter)).setText(StringUtils.getNull(bDeviceEntity.getDParameter()));
            }
        };
        dAdapter.setOnItemClickListener(new SuperAdapter.OnItemClickListener<BDeviceEntity>() {
            @Override
            public void onClick(int i, BDeviceEntity entity) {
                saveData(entity);
            }
        });
        dAdapter.setData(deviceEntities);
        dAdapter.setEmptyDataView(R.layout.view_empty);
        //4：材料物资
        mAdapter = new SuperAdapter<BMaterialEntity>(R.layout.content_add_device) {
            @Override
            public void bindView(ViewHolder viewHolder, final BMaterialEntity bMaterialEntity, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(StringUtils.getNull(bMaterialEntity.getMName()));
                ((TextView) viewHolder.getView(R.id.type)).setText(StringUtils.getNull(bMaterialEntity.getMLabel()));
                ((TextView) viewHolder.getView(R.id.parameter)).setText(StringUtils.getNull(bMaterialEntity.getMParameter()));
            }
        };
        mAdapter.setOnItemClickListener(new SuperAdapter.OnItemClickListener<BMaterialEntity>() {
            @Override
            public void onClick(int i, BMaterialEntity entity) {
                saveData(entity);
            }
        });
        mAdapter.setData(materialEntities);
        mAdapter.setEmptyDataView(R.layout.view_empty);
        //5
        if (pos == 0) {
            rightLView.setAdapter(dAdapter);
        } else {
            rightLView.setAdapter(mAdapter);
        }
        getLeftData();
    }

    //刷新右边数据
    private void getRightData() {
        String search = searchInfo.getText().toString();
        switch (pos) {
            case 0:
                Observable.just(search).subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String search) {
                        deviceEntities.clear();
                        deviceEntities.addAll(SgDBUtils.getBDeviceEntityList(1, leftDatas.get(left), search));
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        dAdapter.notifyDataSetChanged();
                    }
                });
                break;
            case 1:
                Observable.just(search).subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String search) {
                        materialEntities.clear();
                        materialEntities.addAll(SgDBUtils.getBMaterialEntityList(1, leftDatas.get(left), search));
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        mAdapter.notifyDataSetChanged();
                    }
                });
                break;
        }
    }

    //设置物资数据源
    private void getLeftData() {
        final String lable = tvType1.getText().toString().trim();
        left = 0;
        leftDatas.clear();
        switch (pos) {
            case 0://获取设备物资标签
                Observable.just("").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        List<BDeviceEntity> deviceEntityList = SgDBUtils.getBDeviceEntityList(3, "1", lable);
                        for (BDeviceEntity entity : deviceEntityList) {
                            leftDatas.add(entity.getDLabel());
                        }
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        leftAdapter.notifyDataSetChanged();
                        getRightData();
                    }
                });
                break;
            case 1://获取材料物资标签
                Observable.just("").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
                    @Override
                    public Boolean call(String s) {
                        List<BMaterialEntity> materialEntityList = SgDBUtils.getBMaterialEntityList(3, "1", lable);
                        for (BMaterialEntity entity : materialEntityList) {
                            leftDatas.add(entity.getMLabel());
                        }
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        leftAdapter.notifyDataSetChanged();
                        getRightData();
                    }
                });
                break;
        }
    }

    @OnClick({R.id.back_btn, R.id.tvType1, R.id.search_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.search_button:
                getRightData();
                break;
            case R.id.tvType1:
                new ListDialog<String>()
                        .setTitle("选择物资")
                        .setDatas(labels)
                        .setListener(new ResponseListener() {
                            @Override
                            public void response(Object... data) {
                                tvType1.setText(data[0] + "");
                                getLeftData();
                            }
                        }).show(getFragmentManager(), "k");
                break;
        }
    }

    //保存数据
    private void saveData(final Object obj) {
        if (obj instanceof BDeviceEntity) {
            deviceEntities.remove(obj);
        } else if (obj instanceof BMaterialEntity) {
            materialEntities.remove(obj);
        }
        new InputDialog2().setListener(new ResponseListener() {
            @Override
            public void response(Object... data) {
                double count;
                try {
                    count = Double.parseDouble(data[0] + "");
                } catch (NumberFormatException e) {
                    T.showShort(context, "请输入数字");
                    return;
                }
                CGoodsDetailEntity entity = new CGoodsDetailEntity();
                if (obj instanceof BDeviceEntity) {
                    entity.toCGoodsDetailEntity((BDeviceEntity) obj);
                } else if (obj instanceof BMaterialEntity) {
                    entity.toCGoodsDetailEntity((BMaterialEntity) obj);
                }
                entity.setARGuid(uuid);
                entity.setGDNum(count);
                entity.setGDBusine(data[1] + "");
                entity.setPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, "")));
                if (obj instanceof BDeviceEntity) {
                    dAdapter.notifyDataSetChanged();
                } else if (obj instanceof BMaterialEntity) {
                    mAdapter.notifyDataSetChanged();
                }
                SgDBUtils.upDataCGoodsDetailEntity(1, entity);
                T.showShort(context, "添加成功");
            }
        }).show(getFragmentManager(), "" + left);
    }
}
